package com.itheima.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 后台登录的统一鉴权
 */
@Slf4j
@Component
public class AdminAuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取请求地址
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("请求了的地址" + path);
        //2 白名单过滤
        if (path.startsWith("/admin/login")) {
            //这就相当于放行了
            return chain.filter(exchange);
        }
        //3 获取请求头的token
        String token = request.getHeaders().getFirst("token");
        //4 有token
        //判断token是否存在
        if (!StringUtils.isEmpty(token)) {
            //4.1 校验token的有效性
            int verifyToken = AppJwtUtil.verifyToken(token);
            if (SystemConstants.JWT_OK == verifyToken) {
                //4.2 有效就放行,return
                return chain.filter(exchange);
            }
        }

        //否则报错401 未认证
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
/*
//从csdn搜索的过滤器
//https://blog.csdn.net/shudaixiongai/article/details/113178380
@Slf4j
@Component
public class TokenHeaderFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            HttpHeaders headers = exchange.getRequest().getHeaders();
            String cat2Token = headers.getFirst(HttpHeaderCodeEnum.AUTH_TOKEN.code);
            if (Optional.ofNullable(cat2Token).isPresent()) {
                // get user guid
                JSONObject  tokenJson = SignedJWT.parse(cat2Token).getPayload().toJSONObject();
                if (tokenJson.containsKey("sub")) {
                    // set header
                    exchange.getResponse().getHeaders().add("guid", tokenJson.getAsString("sub"));
                }
            }
        } catch (ParseException e) {
           log.error("gateway get jwt error");
        }
        //把新的 exchange放回到过滤链
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return -200;
    }
}

 */
}
